//
//  CXHViewController.m
//  CXHAdSDK-TopOn
//
//  Created by 二跳 on 10/10/2024.
//  Copyright (c) 2024 二跳. All rights reserved.
//

#import "CXHViewController.h"
#import <CXHAdSDK-Kit/CXHUtilsKit.h>
#import <AnyThinkSDK/AnyThinkSDK.h>


@interface CXHViewController ()<ATAdLoadingDelegate, ATNativeADDelegate, ATBannerDelegate, ATInterstitialDelegate>{
    ATNativeADConfiguration *_config;
}

@property (nonatomic, strong) ATNativeADView *nativeADView;

@property (nonatomic, strong) ATBannerView *bannerView;

@end

@implementation CXHViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self loadBanner];
    });
//    [self loadAndShowNativeExpress];
//    [self loadBanner];
//    [self loadAnsShwoInterAd];
    
}

- (void)loadAnsShwoInterAd {
    [self loadInterAd];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self showInterAd];
    });
}

- (void)loadInterAd {
    // 固价：b68bd26854e751
    // 竞价：b68bd26a8b5826
    [[ATAdManager sharedManager] loadADWithPlacementID:@"b68bd26a8b5826" extra:@{} delegate:self];
}

- (void)showInterAd {
    [[ATAdManager sharedManager] showInterstitialWithPlacementID:@"b68bd26a8b5826" inViewController:self delegate:self];
}

#pragma mark -
/// Interstitial ad displayed successfully
- (void)interstitialDidShowForPlacementID:(NSString *)placementID
                                    extra:(NSDictionary *)extra{
    
}

/// Interstitial ad clicked
- (void)interstitialDidClickForPlacementID:(NSString *)placementID
                                     extra:(NSDictionary *)extra{
    
}

/// Interstitial ad closed
- (void)interstitialDidCloseForPlacementID:(NSString *)placementID
                                     extra:(NSDictionary *)extra{
    
}

- (void)loadBanner{
    // 固价：b67079f4bc6c44
    // 竞价：b68bd3c8b72fb5
    NSString *adSlotId = @"b68bd3c8b72fb5";
    
    CGSize size = CGSizeMake(kCXHScreenWidth, kCXHScreenWidth * 5 / 32);
    NSDictionary *extra = @{
        kATAdLoadingExtraBannerAdSizeKey : [NSValue valueWithCGSize:size],
        @"cxh_controller": self,
    };
    [[ATAdManager sharedManager] loadADWithPlacementID:adSlotId extra:extra delegate:self];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        UIView * customView = [UIView new];
        //设置容器的位置与大小，这里大小与广告大小一致
        customView.frame = CGRectMake(0, 100, size.width, size.height);
        //添加容器至当前view中
        [self.view addSubview:customView];
        ATBannerView *bannerView = [[ATAdManager sharedManager] retrieveBannerViewForPlacementID:adSlotId];
        if (bannerView != nil) {
            bannerView.delegate = self;
            bannerView.presentingViewController = self;
            bannerView.translatesAutoresizingMaskIntoConstraints = NO;
            //设置广告bannerView在容器中的位置
            bannerView.frame = customView.bounds;
            self.bannerView = bannerView;
            //将广告view添加至容器中
            [customView addSubview:bannerView];
        }
    });
}

#pragma matk - ATBannerDelegate
/// BannerView display results
- (void)bannerView:(ATBannerView *)bannerView didShowAdWithPlacementID:(NSString *)placementID extra:(NSDictionary *)extra{
    NSLog(@"==========%s", __FUNCTION__);
}

/// bannerView click
- (void)bannerView:(ATBannerView *)bannerView didClickWithPlacementID:(NSString *)placementID extra:(NSDictionary *)extra{
    NSLog(@"==========%s", __FUNCTION__);
}

- (void)loadAndShowNativeExpress {
    NSString *nativeExpressId = @"b68bd36ee60f44";
    NSString *nativeId = @"b68bd356402209";
    
    [self loadNative:nativeExpressId];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self showNative:nativeExpressId];
    });
}

- (void)loadNative:(NSString *)pid {
    CGSize size = CGSizeMake(kCXHScreenWidth, 10);
    NSDictionary *extra = @{
        // 模板广告size，透传给广告平台，广告平台会返回相近尺寸的最优模板广告
        kATExtraInfoNativeAdSizeKey:[NSValue valueWithCGSize:size],
        // 是否开启自适应高度，默认关闭，设置为yes时打开
        kATNativeAdSizeToFitKey:@YES,
//        @"cxh_controller": self,
        @"request_num": @1,
    };
    [[ATAdManager sharedManager] loadADWithPlacementID:pid extra:extra delegate:self];
}

- (void)showNative:(NSString *)pid {
    BOOL ready = [[ATAdManager sharedManager] nativeAdReadyForPlacementID:pid];
    if (ready == NO) {
        NSLog(@"广告位%@，尚未准备就绪。",@"");
        return;
    }
    
    
    // 获取广告offer对象
    ATNativeAdOffer *offer = [[ATAdManager sharedManager] getNativeAdOfferWithPlacementID:pid];
    
    
    // 初始化config配置
    ATNativeADConfiguration *config = [[ATNativeADConfiguration alloc] init];
    config.delegate = self;
    //    // 开启自适应高度
    config.sizeToFit = YES;
    config.rootViewController = self;

        
    // 创建nativeADView
    self.nativeADView = [[ATNativeADView alloc] initWithConfiguration:config currentOffer:offer placementID:pid];
    self.nativeADView.backgroundColor = [UIColor redColor];
    ATNativeAdRenderType nativeAdRenderType = [self.nativeADView getCurrentNativeAdRenderType];
    if (nativeAdRenderType == ATNativeAdRenderExpress) {
        CGFloat adViewWidth = offer.nativeAd.nativeExpressAdViewWidth;
        CGFloat adViewHeight = offer.nativeAd.nativeExpressAdViewHeight;
        config.ADFrame = CGRectMake(0, 100, adViewWidth, adViewHeight);
        config.delegate= self;
        config.rootViewController= self;
        // 渲染广告
        [offer rendererWithConfiguration:config selfRenderView:nil nativeADView:self.nativeADView];
        self.nativeADView.frame = CGRectMake(0, 100, adViewWidth, adViewHeight);
    } else {
        CGFloat width = [UIScreen mainScreen].bounds.size.width - 16 * 2;
        CGFloat height = width * 9 / 16;
        
        config.ADFrame = CGRectMake(16, 100, width, height);
        self.nativeADView.frame = CGRectMake(16, 100, width, height);
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, width, height)];
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, width, height)];
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        imageView.userInteractionEnabled = YES;
        [imageView cxh_setImageWithURL:[NSURL URLWithString:offer.nativeAd.imageUrl]];
        [view addSubview:imageView];
        [self.nativeADView registerClickableViewArray:@[imageView]];
        ATNativePrepareInfo *info = [ATNativePrepareInfo loadPrepareInfo:^(ATNativePrepareInfo * prepareInfo) {
            prepareInfo.mainImageView = imageView;
        }];
        [self.nativeADView prepareWithNativePrepareInfo:info];
        // 渲染广告
        [offer rendererWithConfiguration:config selfRenderView:view nativeADView:self.nativeADView];
    }
    
    
    if (nativeAdRenderType == ATNativeAdRenderExpress) {
        NSLog(@"🔥--原生模板");
        NSLog(@"🔥--原生模板广告宽高：%lf，%lf",offer.nativeAd.nativeExpressAdViewWidth,offer.nativeAd.nativeExpressAdViewHeight);
    }else{
        NSLog(@"🔥--原生自渲染");
    }
    [self.view addSubview:self.nativeADView];
}

/// Callback when the successful loading of the ad
- (void)didFinishLoadingADWithPlacementID:(NSString *)placementID{
    NSLog(@"==========%s", __FUNCTION__);
//    [self showNative];
}

/// Callback of ad loading failure
- (void)didFailToLoadADWithPlacementID:(NSString*)placementID
                                 error:(NSError*)error{
    NSLog(@"==========%s,%@", __FUNCTION__, error);
}

/// Ad start load
- (void)didStartLoadingADSourceWithPlacementID:(NSString *)placementID
                                         extra:(NSDictionary*)extra{
    NSLog(@"==========%s", __FUNCTION__);
}
/// Ad load success
- (void)didFinishLoadingADSourceWithPlacementID:(NSString *)placementID{
    NSLog(@"==========%s", __FUNCTION__);
}
/// Ad load fail
- (void)didFailToLoadADSourceWithPlacementID:(NSString*)placementID
                                       extra:(NSDictionary*)extra
                                       error:(NSError*)error{
    NSLog(@"==========%s=======%@", __FUNCTION__, error);
}

/// Ad start bidding
- (void)didStartBiddingADSourceWithPlacementID:(NSString *)placementID
                                         extra:(NSDictionary*)extra{
    NSLog(@"==========%s", __FUNCTION__);
}

/// Ad bidding success
- (void)didFinishBiddingADSourceWithPlacementID:(NSString *)placementID
                                          extra:(NSDictionary*)extra{
    NSLog(@"==========%s", __FUNCTION__);
}

/// Ad bidding fail
- (void)didFailBiddingADSourceWithPlacementID:(NSString*)placementID
                                        extra:(NSDictionary*)extra
                                        error:(NSError*)error{
    NSLog(@"==========%s, %@", __FUNCTION__, error);
}

- (void)didFinishLoadingADSourceWithPlacementID:(NSString *)placementID extra:(NSDictionary *)extra { 
    
}


- (void)didRevenueForPlacementID:(NSString *)placementID extra:(NSDictionary *)extra { 
    
}


/// Native ads displayed successfully
- (void)didShowNativeAdInAdView:(ATNativeADView *)adView placementID:(NSString *)placementID extra:(NSDictionary *)extra{
    NSLog(@"==========%s", __FUNCTION__);
}

/// Native ad click
- (void)didClickNativeAdInAdView:(ATNativeADView *)adView placementID:(NSString *)placementID extra:(NSDictionary *)extra{
    NSLog(@"==========%s", __FUNCTION__);
    
}

/// Native ads displayed successfully
//- (void)didShowNativeAdInAdView:(ATNativeADView *)adView
//                    placementID:(NSString *)placementID
//                          extra:(NSDictionary *)extra{
//    NSLog(@"==========%s", __FUNCTION__);
//}
//
///// Native ad click
//- (void)didClickNativeAdInAdView:(ATNativeADView *)adView
//                     placementID:(NSString *)placementID
//                           extra:(NSDictionary *)extra{
//    NSLog(@"==========%s", __FUNCTION__);
//}

/// Native video ad starts playing
- (void)didStartPlayingVideoInAdView:(ATNativeADView *)adView
                         placementID:(NSString *)placementID
                               extra:(NSDictionary *)extra{
    NSLog(@"==========%s", __FUNCTION__);
}

/// Native video ad ends playing
- (void)didEndPlayingVideoInAdView:(ATNativeADView *)adView
                       placementID:(NSString *)placementID
                             extra:(NSDictionary *)extra{
    NSLog(@"==========%s", __FUNCTION__);
}

/// Native ad close button cliecked
- (void)didTapCloseButtonInAdView:(ATNativeADView *)adView
                      placementID:(NSString *)placementID
                            extra:(NSDictionary *)extra{
    NSLog(@"==========%s", __FUNCTION__);
    if (self.nativeADView && self.nativeADView.superview) {
        [self.nativeADView removeFromSuperview];
    }
    [self.nativeADView destroyNative];
    self.nativeADView = nil;
}

/// Native ads click to close the details page
/// v5.7.47+
- (void)didCloseDetailInAdView:(ATNativeADView *)adView
                   placementID:(NSString *)placementID
                         extra:(NSDictionary *)extra{
    NSLog(@"==========%s", __FUNCTION__);
}

/// Whether the click jump of Native ads is in the form of Deeplink
/// currently only returns for TopOn Adx ads
- (void)didDeepLinkOrJumpInAdView:(ATNativeADView *)adView
                      placementID:(NSString *)placementID
                            extra:(NSDictionary *)extra
                           result:(BOOL)success{
    NSLog(@"==========%s", __FUNCTION__);
}

/// Native enters full screen video ads, only for Nend
- (void)didEnterFullScreenVideoInAdView:(ATNativeADView *)adView
                            placementID:(NSString *)placementID
                                  extra:(NSDictionary *)extra{
    NSLog(@"==========%s", __FUNCTION__);
}

/// Native exit full screen video ad, only for Nend
- (void)didExitFullScreenVideoInAdView:(ATNativeADView *)adView
                           placementID:(NSString *)placementID
                                 extra:(NSDictionary *)extra{
    NSLog(@"==========%s", __FUNCTION__);
}

@end
